package com.dfd.store.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.dfd.store.dao.CategoryDao;
import com.dfd.store.domain.Category;
import com.dfd.store.utils.JDBCUtils;

public class CategoryDaoImpl implements CategoryDao {
	private QueryRunner runner = new QueryRunner(JDBCUtils.getDataSource());

	@Override
	public List<Category> getAllCats() throws SQLException {
		/*
		 * BeanHandler:表示把结果集中的一行数据，封装成一个对象，专门针对结果集中只有一行数据的情况。
		 * 
		 * BeanListHandler:表示把结果集中的多行数据，封装成一个对象的集合，针对结果集中有多行数据。
		 */
		String sql = "select * from category";

		List<Category> list = runner.query(sql, new BeanListHandler<Category>(Category.class));
		return list;
	}

	@Override
	public Category removeCategory(String cid) throws Exception {
		String sql = "delete from category where cid = ?";
		runner.update(sql, cid);
		return null;
	}

	@Override
	public void save(Category category) throws Exception {
		String sql = "insert into category values (?,?)";
		runner.update(sql, category.getCid(), category.getCname());
	}

	@Override
	public void edit(Category category) throws Exception {
		String sql = "update category set cname=? where cid = ?";
		runner.update(sql, category.getCname(), category.getCid());
	}

	@Override
	public Category findById(String cid) throws Exception {
		String sql = "select * from category where cid = ? ";
		Category category = runner.query(sql, new BeanHandler<Category>(Category.class),cid);
		return category;
	}

}
